<template lang="pug">
.view.cp-manage-store.fix-flex-pos
  //- 查询
  el-form.se-search(:inline="true")
    el-form-item(label="类型 : ")
      el-select(v-model="storeType", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in typeSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="状态 : ")
      el-select(v-model="storeStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in statusSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="搜索类型 : ")
      el-select(v-model="searchType", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="(type, index) in searchTypeSelectAll",
          :key="index", :label="type",
          :value="index")
    el-form-item
      el-input(
        v-model="searchContent",
        placeholder="搜索内容",
        style="width: 160px")
    el-form-item
      el-button(type="primary", @click="searchStores") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addStore") 新建仓库
    //- el-form-item
    //-   el-button(type="primary") 导出
  //- 列表
  .se-table
    el-table(
      :data="storeList",
      highlight-current-row,
      height="100%",
      size="mini", stripe,
      v-loading="loadingStores")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号")
      el-table-column(align="center", show-overflow-tooltip, prop="name", label="名称")
      el-table-column(align="center", show-overflow-tooltip, prop="id", label="编号")
      el-table-column(align="center", show-overflow-tooltip, prop="type", label="类型")
        template(slot-scope="scope")
          span {{ scope.row.type | compare-list(typeSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="address", label="地址")
      el-table-column(align="center", show-overflow-tooltip, prop="keeper", label="仓管员")
        template(slot-scope="scope")
          span {{ scope.row.keeper | compare-list(keeperSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="mobile", label="联系电话")
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="creator", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.creator | compare-list(empSelect) }}
      el-table-column(align="center", label="操作", min-width="90px")
        template(slot-scope="scope")
          el-tooltip(content="查看", @click.native="viewStore(scope.row)")
            i.icon-act.el-icon-view
          el-tooltip(content="编辑", @click.native="eidtStore(scope.row, scope.$index)")
            i.icon-act.el-icon-edit
          el-tooltip(content="删除", @click.native="deleteStore(scope.row, scope.$index)")
            i.icon-act.el-icon-delete
  //- 分页
  el-pagination.se-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeStorePage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="storeListTotal")
  el-dialog.se-dialog(
    :title="dialogTitle",
    :close-on-click-modal="viewStatus",
    :visible.sync="showDialog")
    .se-pop-show(v-show="viewStatus")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 仓库名称 】
          span(v-text="popupObj.name || '未知'")
        el-col(:span="12")
          strong 【 仓库编号 】
          span(v-text="popupObj.id || '未知'")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 状态 】
          span {{ popupObj.status | compare-list(statusSelect) }}
        el-col(:span="12")
          strong 【 仓库类型 】
          span {{ popupObj.type | compare-list(typeSelect) }}
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 创建人 】
          span {{ popupObj.creator | compare-list(empSelect) }}
        el-col(:span="12")
          strong 【 仓管员 】
          span {{ popupObj.keeper | compare-list(keeperSelect) }}
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 部门 】
          span {{ popupObj.department | compare-list(oneDeptSelect) }}
        el-col(:span="12")
          strong 【 联系电话 】
          span(v-text="popupObj.mobile || '未知'")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 上级仓库 】
          span {{ popupObj.upperStorehouse | compare-list(storeSelect) }}
        //- el-col(:span="12")
        //-   strong 【 下级仓库 】
        //-   span {{ popupObj.lowerStorehouse | compare-list(storeSelect) }}
      el-row
        el-col(:span="24")
          strong 【 仓库地址 】
          span(v-text="popupObj.address || '未知'")
      el-row
        el-col(:span="24")
          strong 【 备注 】
          span(v-text="popupObj.remark")
      el-checkbox-group(:disabled="false", :value="checkAllows")
        el-checkbox(:label="0") 启用仓位管理
      el-row(style="margin-top: 6px")
        el-col(:span="24")
          strong 【 仓位数量 】
          span(v-text="popupObj.storageSites || '默认'")
      el-checkbox-group(:disabled="false", :value="checkAllows")
        el-checkbox(:label="1") 允许锁库
        el-checkbox(:label="2") 允许MRP
    el-form.se-pop-form(:inline="true", label-width="72px", v-show="!viewStatus")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="仓库名称")
            el-input(v-model="popupObj.name", placeholder="仓库名称")
        el-col(:span="12")
          el-form-item(label="仓库编号")
            el-input(v-model="popupObj.id", :disabled="true", placeholder="系统自动生成")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="状态")
            el-select(v-model="popupObj.status", placeholder="请选择")
              el-option(v-for="item in statusSelect", :key="item.value", :label="item.name", :value="item.value")
        el-col(:span="12")
          el-form-item.is-required(label="仓库类型")
            el-select(v-model="popupObj.type", placeholder="请选择")
              el-option(
                v-for="item in typeSelect", :key="item.value", :label="item.name", :value="item.value")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="仓管员")
            el-select(v-model="popupObj.keeper", placeholder="请选择")
              el-option(v-for="item in keeperSelect", :key="item.value", :label="item.name", :value="item.value")
        el-col(:span="12")
          el-form-item.is-required(label="联系电话")
            el-input(v-model="popupObj.mobile", placeholder="请输入")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="部门")
            el-select(v-model="popupObj.department", placeholder="请选择")
              el-option(v-for="item in oneDeptSelect", :key="item.value", :label="item.name", :value="item.value")
        el-col(:span="12")
          el-form-item(label="上级仓库")
            el-select(v-model="popupObj.upperStorehouse", placeholder="请选择")
              el-option(v-for="item in storeSelect", :key="item.value", :label="item.name", :value="item.value")
      el-row
        el-col(:span="24")
          el-form-item(label="仓库地址")
            el-input(v-model="popupObj.address", placeholder="请输入")
      el-row
        el-col(:span="24")
          el-form-item(label="备注")
            el-input(v-model="popupObj.remark", placeholder="请输入")
      el-row.se-set-pos0(:gutter="36")
        el-col(:span="12")
          el-form-item(label="仓位")
            el-checkbox-group(v-model="checkAllows")
              el-checkbox(:label="0") 启用仓位管理
        el-col(:span="12")
          el-form-item(label="仓位数量", :class="(checkAllows.indexOf(0) < 0) ? '' : 'is-required'")
            el-input-number(v-model="popupObj.storageSites", :min="1", :max="10")
      el-row.se-set-pos1
        el-col(:span="24")
          el-form-item(label="设置")
            el-checkbox-group(v-model="checkAllows")
              el-checkbox(:label="1") 允许锁库
              el-checkbox(:label="2") 允许MRP
    el-row(v-show="!viewStatus")
      el-col(:span="24", style="text-align: center;")
         el-button(type="primary", style="width: 80px;", plain, @click="closeDialog") 取消
         el-button(type="primary", style="width: 80px; margin-left: 40px;", @click="saveStore") 确定
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ManApi from '@/api/manage';
import check from './check';

export default {
  name: 'invstore',
  data() {
    return {
      storeType: null,
      storeStatus: null,
      searchType: 0,
      searchContent: '',
      searchTypeSelectAll: ['仓库名称', '仓管员', '仓库ID'],
      //
      storeList: [],
      storeListTotal: 1,
      loadingStores: true,
      currentPage: 1,
      pageSize: 20,
      // 显示弹层
      showDialog: false,
      dialogTitle: '新建仓库',
      viewStatus: false,
      // 弹层
      typeSelect: [],
      typeSelectAll: [],
      statusSelect: [],
      statusSelectAll: [],
      keeperSelect: [],
      popupObj: {},
      checkAllows: []
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'storeSelect', 'oneDeptSelect', 'employeeId'])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    openDialog () {
      this.showDialog = true;
    },
    closeDialog () {
      this.showDialog = false;
    },
    resetSearch () {
      this.storeType = null;
      this.storeStatus = null;
      this.searchType = 0;
      this.searchContent = '';
    },
    makeSearch () {
      const params = {};
      if (typeof this.storeType !== 'object') {
        params.type = this.storeType;
      }
      if (typeof this.storeStatus !== 'object') {
        params.status = this.storeStatus;
      }
      const props = ['name', 'keeper', 'id'];
      if (this.searchContent) {
        params[props[this.searchType]] = this.searchContent;
      }

      return params;
    },
    searchStores () {
      const params = this.makeSearch();
      this.loadingStores = true;
      ManApi.getStoreList(params).then((result) => {
        if (!result.status) {
          this.storeList = result.obj.records;
          this.storeListTotal = result.obj.totalNum;
          this.currentPage = 1;
        } else {
          this.$message.error(result.comment);
        }
        this.loadingStores = false;
      }).catch((error) => {
        this.$message.error('网络不给力，请稍后再试');
        this.loadingStores = false;
        console.log(JSON.stringify(error));
      });
    },
    // 仓库增删改查
    addStore () {
      this.dialogTitle = '新建仓库';
      this.popupObj = {};
      this.viewStatus = false;
      this.openDialog();
    },
    handlePushAllows () {
      // 初始化锁库和MPR
      const allowingSite = !!this.popupObj.allowingSite;
      if (allowingSite) {
        this.checkAllows.push(0);
      }
      const allowingLock = !!this.popupObj.allowingLock;
      if (allowingLock) {
        this.checkAllows.push(1);
      }
      const allowingMRP = !!this.popupObj.allowingMRP;
      if (allowingMRP) {
        this.checkAllows.push(2);
      }
    },
    handleSaveAllows () {
      if (this.checkAllows.indexOf(0) >= 0) {
        this.popupObj.allowingSite = 1;
      } else {
        this.popupObj.allowingSite = 0;
      }
      // 允许锁库或者MPR
      if (this.checkAllows.indexOf(1) >= 0) {
        this.popupObj.allowingLock = 1;
      } else {
        this.popupObj.allowingLock = 0;
      }
      if (this.checkAllows.indexOf(2) >= 0) {
        this.popupObj.allowingMRP = 1;
      } else {
        this.popupObj.allowingMRP = 0;
      }
    },
    viewStore (row) {
      this.dialogTitle = '查看仓库';
      ManApi.getStoreDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.handlePushAllows();
          this.viewStatus = true;
          this.openDialog();
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(error);
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    eidtStore (row, index) {
      this.focusIndex = index;
      this.dialogTitle = '编辑仓库';
      ManApi.getStoreDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.handlePushAllows();
          this.viewStatus = false;
          this.openDialog();
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(error);
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    deleteStore (row, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingStores = true;
        ManApi.deleteStore({ id: row.id }).then((result) => {
          if (!result.status) {
            this.storeList.splice(index, 1);
            this.storeListTotal = this.storeListTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
          this.loadingStores = false;
        }).catch((error) => {
          console.log(error);
          this.$message.error('网络不给力，请稍后再试');
          this.loadingStores = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveStore () {
      this.handleSaveAllows();
      const canSave = check(this.popupObj);
      if (canSave) {
        ManApi.saveStore(this.popupObj).then((result) => {
          if (!result.status) {
            this.$message.success('保存成功');
            if (this.popupObj.id) {
              this.$set(this.storeList, this.focusIndex, result.obj);
            } else {
              this.storeList.unshift({});
              this.$set(this.storeList, 0, result.obj);
              this.storeListTotal += 1;
              if (this.storeListTotal > 20) {
                this.storeList.pop();
              }
            }
            this.closeDialog();
          } else {
            this.$message.error(`保存失败：${result.comment}`);
          }
        }).catch((error) => {
          console.log(error);
          this.$message.error('网络不给力，请稍后再试');
          this.loadingStores = false;
        });
      }
    },
    // 监听对Store列表操作事件
    clickStoreRow (row) {
      console.log(row);
    },
    dbClickStoreRow (row) {
      this.viewStore(row);
    },
    // 分页
    changeStorePage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingStores = true;
      ManApi.getStoreList(params).then((result) => {
        if (!result.status) {
          this.storeList = result.obj.records;
          this.storeListTotal = result.obj.totalNum;
          this.currentPage = currentPage;
        } else {
          this.$message.error(result.comment);
        }
        this.loadingStores = false;
      }).catch((error) => {
        this.$message.error('网络不给力，请稍后再试');
        this.loadingStores = false;
        console.log(JSON.stringify(error));
      });
    }
  },
  created () {
    // 类型列表
    ComApi.getTypes({ orderType: 'storehouse' }).then((tyspList) => {
      this.typeSelect = tyspList;
      this.typeSelectAll = [{ name: '全部', value: null }].concat(tyspList);
    });
    // 状态列表
    ComApi.getStatus({ orderType: 'storehouse' }).then((statusList) => {
      this.statusSelect = statusList;
      this.statusSelectAll = [{ name: '全部', value: null }].concat(statusList);
    });
    // 获取仓管员
    ComApi.getStoreAllKeepers().then((keeperList) => {
      this.keeperSelect = keeperList;
    });
  },
  mounted () {
    ManApi.getStoreList().then((result) => {
      if (!result.status) {
        this.storeList = result.obj.records;
        this.storeListTotal = result.obj.totalNum;
      } else {
        this.$message.error(result.comment);
      }
      this.loadingStores = false;
    }).catch((error) => {
      this.loadingStores = false;
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-manage-store
  .se-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .se-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $PAGEHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    table
      width: 100%
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
  .se-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
  .el-dialog__body
    padding: 24px 36px 28px 40px
  .se-pop-show
    overflow: hidden
    .el-row
      margin-bottom: 12px
      &:nth-child(odd)
        background: #f5f5f5
      &:nth-child(even)
        background: beige
    strong
      display: inline-block
      font-weight: 400
      margin-right: 8px
    .el-checkbox-group
      padding-left: 8px
  .se-pop-form
    .el-form-item
      width: 100%
      margin-right: 0
    .el-form-item__content
      width: calc(100% - 72px)
    .el-form-item__label
      text-align: left
    .el-select
      width: 100%
    .se-set-pos0
      postion: relative
      top: 4px
    .se-set-pos1
      postion: relative
      top: -8px
  .se-part-line
    border-top: 1px solid #dcdfe6
    margin-bottom: 16px
    margin-top: 24px
</style>
